package org.wupuser.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupuser.model.Banner;

import java.time.Instant;
import java.util.List;

@Repository
public interface BannerRepository extends JpaRepository<Banner, Long> {
	@Query(nativeQuery = true, value = "select * from banner")
	List<Banner> findAll();
	
	@Query(nativeQuery = true, value = "select * from banner where username like CONCAT('%',:username,'%')")
	List<Banner> findByUsername(@Param("username") String username);
	
	@Query(nativeQuery = true, value = "select * from banner where ban_time = :banTime")
	List<Banner> findByBanTime(@Param("banTime") Instant banTime);
	
	@Query(nativeQuery = true, value = "select * from banner where uuid = :uuid")
	Banner findByUuid(@Param("uuid") String uuid);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "insert into banner(ban_time, ban_end_time, username, uuid) values(:#{#banner.banTime}, :#{#banner.banEndTime}, :#{#banner.username}, :#{#banner.uuid})")
	void saveBanner(@Param("banner") Banner banner);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "delete from banner where ban_end_time < :currentTime")
	void deleteByTime(@Param("currentTime") Instant currentTime);
}
